#include "TowerBase.h"
#include "Wave.h"
#include "EnemyBase.h"
#include "GamePlayMediator.h"
#include "TexturePool.h"

#include <iostream>

TowerBase::TowerBase(void):Sprite()
{
	ammoDamage.value = 0;
}


TowerBase::~TowerBase(void)
{

}

void TowerBase::waveInteract(Wave * wave)
{

	if(wave->size() > 0)
	{
		if(wave->getNumberOfActiveEnemies() > 0)
		{
			

			if(count < shootRate)
			count ++;

			//std::cout << count <<std::endl;
			if(count == shootRate)
			{
				
				for(int i = 0;i<wave->getNumberOfActiveEnemies();i++)
				{
					EnemyBase * enemy = wave->getElementByIndex(i);
					if(enemy->getDistanceFromCentral(this) <= range.getValue())
					{
						
						shoot(enemy);
						count = 0;
						break;
					}

				}
	
			}
		}
	}


}
void TowerBase::init()
{
	ammoDamage.type = BASIC;
	showRange(true);
	texture = TexturePool::getPtr()->getTexture("Data/Towers/turret.png",area.w,area.h);
	range.setValue(50);

	count = 69;


}
void TowerBase::destroy()
{

}

void TowerBase::setDamageValue(double dmgValue)
{
	ammoDamage.value = dmgValue;
}

double TowerBase::getDamageValue()
{
	return ammoDamage.value;
}

Ammo * TowerBase::createAmmo()
{
	Ammo * ammo = new Ammo;
	ammo->setDamageValue(ammoDamage.value);
	ammo->setSpeed(3);
	return ammo;
}


void TowerBase::setRangeValue(double val)
{
	range.setValue(val);
	range.centerToPoint(getCenterX(),getCenterY());
}
double TowerBase::getRangeValue()
{
	return range.getValue();
}

void TowerBase::showRange(bool val)
{
	range.setVisible(val);
}

void TowerBase::draw(SDL_Renderer * renderer)
{
	if(isVisible())
	{
		range.draw(renderer);
		SDL_RenderCopy(renderer,texture,NULL,&area);
	}
}

void TowerBase::shoot(EnemyBase * enemy)
{

	Ammo * ammo = createAmmo();

	ammo->setPosition(getCenterX(),getCenterY());
	ammo->init();
	ammo->setEnemyTarget(enemy);

	GamePlayMediator::getPtr()->getArena()->addAmmo(ammo);


}

void TowerBase::onAreaChange()
{
	range.centerToPoint(getCenterX(),getCenterY());
}

void TowerBase::setShootRate(int rate)
{
	shootRate = rate;
	count = rate;
}
int TowerBase::getShootRate()
{
	return shootRate;
}

SDL_Rect TowerBase::getInteractionArea()
{
	return area;
}

void TowerBase::onClick()
{
	if(range.isVisible())
		showRange(false);
	else 
		showRange(true);
}

TowerBase * TowerBase::copy()
{
	TowerBase * t = new TowerBase();
	t->texture = texture;
	t->setRangeValue(range.getValue());
	t->setWidth(getWidth());
	t->setHeight(getHeight());
	t->setDamageValue(getDamageValue());
	t->setShootRate(getShootRate());
	t->setPosition(getX(),getY());
	t->showRange(range.isVisible());
	t->count = 0;
	return t;
}

void TowerBase::setAmmoSpeed(int ammoSpeed)
{
	this->ammoSpeed = ammoSpeed;
}
int TowerBase::getAmmoSpeed()
{
	return ammoSpeed;
}

bool TowerBase::isRangeVisible()
{
	return range.isVisible();
}
